<template>
  <div class="publish-container">
    <!-- 封装后的导航栏 -->
    <div class="custom-nav-wrapper">
      <t-navbar title="发布动态" :fixed="false" class="custom-navbar">
        <template #left>
          <t-button theme="default" variant="text" @click="tzMood">
            <icon-font name="close" class="btn-icon" />取消
          </t-button>
        </template>
        <template #right>
          <t-button
            theme="primary"
            shape="round"
            @click="addMood"
            :disabled="!mood.content.trim()"
            class="publish-btn"
          >
            <icon-font name="send" class="btn-icon" />发布
          </t-button>
        </template>
      </t-navbar>
    </div>

    <!-- 主内容区 -->
    <div class="content-wrapper">
      <!-- 输入区域 -->
      <div class="input-section">
        <t-textarea
          v-model="mood.content"
          placeholder="分享你的陪玩心得，优质内容有机会获得推荐..."
          :autosize="{ minRows: 4, maxRows: 8 }"
          :maxlength="500"
          borderless
          class="custom-textarea"
        />
        <div class="counter">{{ mood.content.length }}/500</div>
      </div>

      <!-- 媒体上传组件 -->
      <div class="media-uploader-section">
        <t-upload
          multiple
          :files="imgs"
          :max="6"
          action="http://localhost:8181/api/file/uploadimg"
          :on-success="uploadSuccess"
          theme="custom"
          class="media-uploader"
        >
          <template #trigger>
            <div class="upload-card">
              <icon-font name="image" class="upload-icon" />
              <span class="upload-text">添加图片/视频</span>
            </div>
          </template>
          <template #file-list="params">
            <div class="preview-grid">
              <div
                v-for="(file, index) in params.files"
                :key="file.name"
                class="preview-item"
              >
                <img :src="file.url" class="preview-image" />
                <icon-font
                  name="close-circle"
                  class="delete-icon"
                  @click="removeImage(index)"
                />
              </div>
            </div>
          </template>
        </t-upload>
      </div>

      <!-- 附加信息 -->
      <div class="additional-info">
        <!-- 位置 -->
        <div class="location-card" @click="selectLocation">
          <icon-font name="map-pin" class="location-icon" />
          <div class="location-info">
            <div class="location-title">所在位置</div>
            <div class="location-address">
              {{ mood.address || "点击添加位置" }}
              <span v-if="!mood.address" class="location-hint">(需允许定位权限)</span>
            </div>
          </div>
          <icon-font name="chevron-right" class="arrow-icon" />
        </div>

        <!-- 话题 -->
        <div class="topic-section">
          <div class="section-title">关联话题</div>
          <div class="topic-tags">
            <t-tag
              v-for="(tag, index) in trendingTopics"
              :key="index"
              shape="round"
              variant="outline"
              class="topic-tag"
              @click="selectTopic(tag)"
            >
              #{{ tag }}
            </t-tag>
          </div>
        </div>

        <!-- 隐私设置 -->
        <div class="privacy-section">
          <div class="section-title">隐私设置</div>
          <t-radio-group v-model="mood.privacy" variant="default-filled">
            <t-radio value="public" class="privacy-option">
              <icon-font name="earth" /> 公开
            </t-radio>
            <t-radio value="private" class="privacy-option">
              <icon-font name="lock" /> 仅自己
            </t-radio>
          </t-radio-group>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { post } from "../util/Request";
import { Toast } from "tdesign-mobile-vue";

const router = useRouter();
const imgs = ref<any[]>([]);
const trendingTopics = ref(["游戏陪玩", "语音连麦", "技能分享", "组队开黑", "经验交流"]);

type Mood = {
  uid: number;
  content: string;
  type: string;
  address: string;
  privacy: string;
  img1: string;
  img2: string;
  img3: string;
  img4: string;
  img5: string;
  img6: string;
  [key: string]: any; // Index signature
};

// 动态数据
const mood = ref<Mood>({
  uid: Number(sessionStorage.getItem("uid")),
  content: "",
  type: "文本",
  address: "",
  privacy: "public",
  img1: "",
  img2: "",
  img3: "",
  img4: "",
  img5: "",
  img6: ""
});

//取消，返回动态页面
const tzMood = async () => {
  await router.push("/mood");
};
// 发布动态
const addMood = async () => {
  if (!mood.value.content.trim()) {
    return Toast("请填写发布内容");
  }

  try {
    const res = await post("mood/add", mood.value);
    if (res.data.code === 200) {
      Toast.success("发布成功");
      await router.push("/mood");
    } else {
      Toast(res.data?.data || "发布失败");
      await router.push("/mood");
    }
  } catch (error) {
    Toast("网络请求失败");
  }
};

// 上传成功处理
const uploadSuccess = ({ file }: any) => {
  const imgField = `img${imgs.value.length + 1}`;
  if (imgField in mood.value) {
    mood.value[imgField] = file.response.data;
  }
};
// 选择话题
const selectTopic = (topic: string) => {
  if (!mood.value.content.includes(`#${topic}`)) {
    mood.value.content += ` #${topic}`;
  }
};

// 移除图片
const removeImage = (index: number) => {
  imgs.value.splice(index, 1);
  // 重置图片字段
  Object.keys(mood.value).forEach((key, i) => {
    if (key.startsWith("img")) mood.value[key] = i < imgs.value.length ? imgs.value[i].url : "";
  });
};

// 腾讯地图KEY（请替换为你的实际KEY）
const TENCENT_MAP_KEY = "NQ3BZ-ZMZY3-KN53J-OJQSI-47ZDH-DHBEK";

// 选择位置
const selectLocation = async () => {
  Toast.loading("获取位置中...");
  try {
    // 1. 获取用户经纬度
    const position = await getCurrentPosition();
    const { latitude, longitude } = position.coords;
    
    // 2. 调用腾讯逆地理编码API
    const address = await getTencentGeocoder(latitude, longitude);
    
    mood.value.address = address || "未知位置";
    Toast.clear();
  } catch (error) {
    console.error("定位失败:", error);
    Toast("获取位置失败");
    // 后备方案：允许手动输入
    const manualAddress = window.prompt("请手动输入您的位置", "郑州市高新区");
    if (manualAddress) {
      mood.value.address = manualAddress;
    }
  }
};

// 获取当前位置
const getCurrentPosition = (): Promise<GeolocationPosition> => {
  return new Promise((resolve, reject) => {
    if (!navigator.geolocation) {
      reject("浏览器不支持定位");
      return;
    }
    
    navigator.geolocation.getCurrentPosition(
      resolve,
      (error) => {
        reject(getGeolocationError(error));
      },
      { 
        enableHighAccuracy: true, 
        timeout: 10000,
        maximumAge: 0
      }
    );
  });
};

// 腾讯逆地理编码
const getTencentGeocoder = async (lat: number, lng: number): Promise<string> => {
  const url = `/map-api/ws/geocoder/v1/?location=${lat},${lng}&key=${TENCENT_MAP_KEY}&get_poi=1`;
  
  try {
    const response = await fetch(url);
    const data = await response.json();
    
    if (data.status === 0) {
      return data.result.address;
    } else {
      throw new Error(data.message || "逆地理编码失败");
    }
  } catch (error) {
    console.error("腾讯地图API错误:", error);
    throw error;
  }
};

// 处理定位错误信息
const getGeolocationError = (error: GeolocationPositionError): string => {
  switch(error.code) {
    case error.PERMISSION_DENIED:
      return "用户拒绝了定位请求";
    case error.POSITION_UNAVAILABLE:
      return "位置信息不可用";
    case error.TIMEOUT:
      return "获取位置超时";
    default:
      return "定位失败";
  }
};

// 初始化时尝试获取位置（可选）
onMounted(async () => {
  try {
    const position = await getCurrentPosition();
    const address = await getTencentGeocoder(
      position.coords.latitude,
      position.coords.longitude
    );
    mood.value.address = address;
  } catch (error) {
    console.log("初始化定位失败:", error);
  }
});
</script>

<style scoped>
/* 整体容器 */
.publish-container {
  background: linear-gradient(135deg, #f5f6fa 0%, #e8eaf6 100%);
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 导航栏包装器 */
.custom-nav-wrapper {
  background: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  z-index: 100;
}

/* 内容包装器 */
.content-wrapper {
  padding: 24px;
  flex: 1;
  overflow-y: auto;
}

/* 输入区域 */
.input-section {
  background: white;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s ease-in-out;
}

.input-section:hover {
  transform: translateY(-2px);
}

.custom-textarea {
  font-size: 18px;
  line-height: 1.6;
  --td-textarea-placeholder-color: #90a4ae;
}

.counter {
  text-align: right;
  color: #90a4ae;
  font-size: 14px;
  margin-top: 12px;
}

/* 媒体上传部分 */
.media-uploader-section {
  background: white;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  margin-top: 24px;
  transition: transform 0.2s ease-in-out;
}

.media-uploader-section:hover {
  transform: translateY(-2px);
}

.upload-card {
  border: 2px dashed #cfd8dc;
  border-radius: 12px;
  height: 120px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #90a4ae;
  transition: all 0.3s;
}

.upload-card:hover {
  border-color: var(--td-brand-color);
  background: #f8f9fe;
  transform: scale(1.02);
}

.upload-icon {
  font-size: 28px;
  margin-bottom: 10px;
}

.preview-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
  margin-top: 16px;
}

.preview-item {
  position: relative;
  aspect-ratio: 1;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.delete-icon {
  position: absolute;
  top: 6px;
  right: 6px;
  color: white;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  cursor: pointer;
  font-size: 18px;
  transition: transform 0.2s ease-in-out;
}

.delete-icon:hover {
  transform: scale(1.1);
}

/* 附加信息部分 */
.additional-info {
  margin-top: 24px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.location-card,
.topic-section,
.privacy-section {
  background: white;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s ease-in-out;
}

.location-card:hover,
.topic-section:hover,
.privacy-section:hover {
  transform: translateY(-2px);
}

.location-icon {
  color: var(--td-brand-color);
  font-size: 24px;
  margin-right: 16px;
}

.location-info {
  flex: 1;
}

.location-title {
  font-size: 16px;
  color: #37474f;
  font-weight: 500;
}

.location-address {
  font-size: 14px;
  color: #607d8b;
  margin-top: 4px;
}

.section-title {
  font-size: 16px;
  color: #37474f;
  font-weight: 500;
  margin-bottom: 12px;
}

.topic-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.topic-tag {
  background: #f5f5f5;
  color: var(--td-brand-color);
  border-color: #e0e0e0;
  cursor: pointer;
  transition: all 0.2s ease-in-out;
}

.topic-tag:hover {
  background: #e0e0e0;
  transform: scale(1.05);
}

.privacy-option {
  margin-right: 24px;
  font-size: 16px;
}

.btn-icon {
  margin-right: 6px;
}

.publish-btn {
  padding: 8px 20px;
  font-size: 16px;
}

.location-hint {
  color: #90a4ae;
  font-size: 12px;
  margin-left: 6px;
}
</style>